//
//  ScrollView.m
//  Go!
//
//  Created by rimi on 16/7/7.
//  Copyright © 2016年 黄秋燕. All rights reserved.
//


#import "HQYFoodScrollView.h"
#import "NetWorkManager.h"
#import "UIImageView+WebCache.h" // 图片缓存

#define IMAGE_NUM [self.model getNumberOfRows]
#define Food_SCROLL_VIEW_H Size_H(120)
@implementation HQYFoodScrollView
- (void)dealloc {
    // 移除观察者
    [self.model removeObserver:self forKeyPath:@"response"];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self.model getList];
        [self.model addObserver:self forKeyPath:@"response" options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

// 监听到状态变化会执行该方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"response"]) {
        [self setupSubsView];
    }
}

- (void)setupSubsView {
    [self addSubview:self.scrollView];
    [self addScrollImage];
    [self addSubview:self.pageControl];
}

#pragma mark - 添加图片的方法
- (void)addScrollImage {
    _imageArr = [self.model getDataArray];
    for (NSInteger index = 0; index < IMAGE_NUM; index++) {
        //初始化图片视图
        UIImageView *imageView = [[UIImageView alloc]init];
        //图片充满scrollView的全部
        imageView.frame = CGRectMake(index * ScreenW, 0, ScreenW, Food_SCROLL_VIEW_H);
        //使用数组添加图片
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.imageArr[index]] placeholderImage:[UIImage imageNamed:@"等待中"]];
        //添加图片视图到scrollView
        [self.scrollView addSubview:imageView];
    }
    //添加完图片后，根据图片数量设置滚动范围
    self.scrollView.contentSize = CGSizeMake(ScreenW * IMAGE_NUM, 0);
    //添加分页控制器并设置初始点
    self.pageControl.currentPage = 0;
    //开启定时器
    [self startTimer];
}

#pragma mark - 定时器
//自动改变滚动视图的偏移量
- (void)autoScrollImage {
    //获得当前偏移量
    CGFloat offset = self.scrollView.contentOffset.x;
    //增加一张图片的宽度后，重新设置偏移量
    CGFloat newOffset = offset + ScreenW;
    //设置偏移量(使用带动画模式的方法)
    [self.scrollView setContentOffset:CGPointMake(newOffset, 0) animated:YES];
}

- (void)startTimer {
    //定时器为空的时候才初始化定时器
    if (!self.timer) {
        //启动定时器
        self.timer  = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(autoScrollImage) userInfo:nil repeats:YES];
    }
}

//停止定时器
- (void)stopTimer {
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark - 代理方法
//滚动图片时，会不断调用（调用频率很高，非必要不使用）
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //获得偏移量
    CGFloat offset = scrollView.contentOffset.x;
    //计算当前图片的页数
    NSInteger page = offset/ScreenW + 0.5;
    self.pageControl.currentPage = page - 1;
}

//滚动停止的时候调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //先获得当前的偏移量
    CGFloat currentOffset = scrollView.contentOffset.x;
    //判断是否是最后一张图片
    if (currentOffset > ScreenW * (IMAGE_NUM - 2)) {
        scrollView.contentOffset = CGPointMake(ScreenW, 0);
    }
    if (currentOffset < ScreenW) {
        scrollView.contentOffset = CGPointMake(ScreenW * (IMAGE_NUM-2), 0);
    }
}

//人为拖动即将开始的时候
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    //开始手动拖动图片的时候停止定时器
    [self stopTimer];
}

//人为拖动结束的时候调用
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    //结束拖动时，重新开启定时器
    [self startTimer];
}

//启用动画的时候只调用(非人为拖动)
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    //调用写了切换图片代码的代理方法
    [self scrollViewDidEndDecelerating:scrollView];
}

#pragma mark - 懒加载
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]init];
        _scrollView.frame = CGRectMake(0, 0, ScreenW, Food_SCROLL_VIEW_H);
        _scrollView.delegate = self;
        //设置分页效果
        _scrollView.pagingEnabled = YES;
        //主动设置默认偏移一张图片
        _scrollView.contentOffset = CGPointMake(ScreenW, 0); //设置偏移量
        //关闭弹簧效果
        _scrollView.bounces = NO;
        _scrollView.alwaysBounceHorizontal = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    
    return _scrollView;
}

//分页控制器
- (UIPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc]init];
        _pageControl.frame = CGRectMake((ScreenW - 100)/2, Food_SCROLL_VIEW_H - 30, 100, 30);
        
        //设置分页器的点个数
        _pageControl.numberOfPages = IMAGE_NUM - 2;
        //设置未被选中的点的颜色
        _pageControl.pageIndicatorTintColor = ColorWith(180, 180, 180);
        //设置被选中点的颜色
        _pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    }
    
    return _pageControl;
}

- (HQYFoodScrollViewModel *)model {
    if (!_model) {
        _model = [[HQYFoodScrollViewModel alloc] init];
    }
    return _model;
}

@end
